package com.hand.lwf24378.materials.exception;

import com.hand.lwf24378.materials.domain.Result;
import com.hand.lwf24378.materials.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

/**
 * @author : WaveLee
 * @date : 2019/7/19 14:44
 * @description : 异常处理类
 */
@ControllerAdvice
public class HandleExceptions {

    private final static Logger logger = LoggerFactory.getLogger(HandleExceptions.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result<Object> handle(Exception e) {
        if (e instanceof MaterialsException) {
            // 自定义异常
            MaterialsException materialsException = (MaterialsException) e;
            return ResultUtil.error(materialsException);
        } else if (e instanceof MethodArgumentTypeMismatchException) {
            logger.error("【系统异常】 {}", e.getMessage());
            // 参数类型不匹配
            return ResultUtil.error(new MaterialsException(EnumExceptions.ARGB_MISMATCH_EXCEPTION));
        } else {
            logger.error("【系统异常】 {}", e.getMessage());

            if (e.getMessage().contains("Request method")) {
                // 请求方法不匹配
                return ResultUtil.error(new MaterialsException(EnumExceptions.REQUEST_METHOD));
            } else {
                return ResultUtil.error(new MaterialsException(EnumExceptions.UNKNOWN_ERROR));
            }
        }
    }
}
